/**
 * Created by wry on 2015/4/2.
 */

var toolUtil = require('../common/utils/toolUtil');
var messageUtil = require('../common/utils/messageUtil');
var Users = mongoose.model('user');
var async = require('async');
var scoreService = require('../services/score-service');


/**
 * 获取个人积分信息
 * @param req
 * @param res
 */
exports.getUserScore = function (req, res) {
    var token = req.params.token;


    scoreProxy.invoke('getScoreInfoByUid', [token], function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserScore ...!');
            res.json(messageUtil.composeFailedMessage(req, '获取情值失败', 1201));
        } else {
            logger.info(result);
            var data = JSON.parse(decodeURIComponent(result));
            logger.info(data);
            if (data.status != 0) {
                logger.error('getUserScore----' + data.msg);
                res.json(messageUtil.composeFailedMessage(req, data.msg, 1201));
            } else {
                var temp = {
                    currentValue: data.data.scoreInfo.currentValue + ''
                };
                res.json(messageUtil.composeSucceededMessage(req, null, temp, 1201));
            }
        }
    });
};

/**
 * 获取积分增加记录
 * @param req
 * @param res
 */
exports.getUserScoreAddRecord = function (req, res) {

    var token = req.params.token;
    var page = req.params.pageNo;
    var vcode = req.cparams.vcode;


    var input = {
        userId: token,
        pageNum: Number(page)
    };

    scoreAddProxy.invoke('getScoreAddRecordForPage', [input], function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserScoreAddRecord ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1202));
        } else {
            var data = JSON.parse(decodeURIComponent(result));
            if (data.status != 0) {
                logger.error('getUserScoreAddRecord----' + data.msg);
                res.json(messageUtil.composeFailedMessage(req, data.msg, 1202));
            } else {
                var temp = data.data.addRecordList;

                logger.info(Number(vcode))
                temp.forEach(function (record) {
                    record.updateTime = new Date(record.updateTime * 1000);
                    record.newChangeValue = record.changeValue >= 0 ? '+' + record.changeValue : record.changeValue + '';
                });
                res.json(messageUtil.composeSucceededMessage(req, null, temp, 1202));
            }
        }
    });
};


/**
 * 获取积分消费记录
 * @param req
 * @param res
 */
exports.getUserScoreConsumeRecord = function (req, res) {

    var token = req.params.token;
    var page = Number(req.params.pageNo);

    var input = {
        userId: token,
        pageNum: page
    };

    exchangeProxy.invoke('getScoreExchangeForUser', [input], function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserScoreConsumeRecord ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1203));
        } else {
            var data = JSON.parse(decodeURIComponent(result));
            if (data.status != 0) {
                logger.error('getUserScoreConsumeRecord----' + data.msg);
                res.json(messageUtil.composeFailedMessage(req, data.msg, 1203));
            } else {
                var temp = data.data.recordList;
                temp.forEach(function (record) {
                    record.updateTime = new Date((record.status == 0 ? record.createTime : record.updateTime) * 1000);
                    record.createTime = new Date(record.createTime * 1000);
                    if (record.status == 2) {
                        record.status = 0;
                    }
                });
                res.json(messageUtil.composeSucceededMessage(req, null, temp, 1203));
            }
        }
    });
};

/**
 * 获取商品列表（app）
 * @param req
 * @param res
 */
exports.getScoreShopList = function (req, res) {
    var pageNo = Number(req.params.pageNo);

    productProxy.invoke('getScoreShopForUser', [pageNo], function (err, result) {
        if (err) {
            logger.error('Exception happened when getScoreShopList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1204));
        } else {

            var data = JSON.parse(decodeURIComponent(result)).data.productList;
            data.forEach(function (temp) {
                temp.createTime = new Date(temp.createTime * 1000);
                //if (temp.images != null) {
                //    var t = temp.images.split('.');
                //    temp.images = t[0] + '_250-250.png'
                //}
            });

            res.json(messageUtil.composeSucceededMessage(req, null, data, 1204));
        }
    })
};

/**
 * 兑换商品
 * @param req
 * @param res
 */
exports.exchangeGoods = function (req, res) {
    var token = req.params.token;
    var input = req.body;

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            logger.error('Exception happened when exchangeGoods ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 1205));
        } else {
            var temp = {
                uid: token,
                productId: input.productId,
                exchangeNum: input.exchangeNum,
                mobile: input.mobile,
                address: input.roomUnit + '单元' + input.roomNumber + '房号',
                userName: encodeURIComponent(input.userName),
                desc: input.desc
            };

            exchangeProxy.invoke('exchangeProduct', [temp], function (err, result) {
                if (err) {
                    logger.error('Exception happened when exchangeGoods ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message, 1205));
                } else {

                    var data = JSON.parse(decodeURIComponent(result));

                    if (data.status != 0) {
                        logger.error('exchangeGoods---' + data.msg);
                        res.json(messageUtil.composeFailedMessage(req, data.msg));
                    } else {
                        var temp = {
                            currentValue: data.data.currentValue + ''
                        };
                        res.json(messageUtil.composeSucceededMessage(req, null, temp, 1205));

                        var message = '已收到您的兑换申请，小6将尽快为您兑换，如有疑问，请随时联系小6';
                        toolUtil.pushCustomerServiceMessage(user, message);
                    }
                }
            });
        }
    });
};


//========================================后台积分=======================================


/**
 * 增加商品
 * @param req
 * @param res
 */
exports.addGoods = function (req, res) {
    var input = req.body;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload Images... - ' + err.message));
        } else {
            var data = new Array();

            images.forEach(function (image) {
                if (image != null) {
                    data.push(image);
                }
            });


            input.inventoryLevel = Number(input.inventoryLevel);
            input.price = Number(input.price);
            input.images = data[0];
            input.status = 0;
            input.__type__ = 'com.neighborhoods.data.domain.score.ScoreShopEntity';


            productProxy.invoke('saveScoreShop', [input], function (err, result) {
                if (err) {
                    logger.error('Exception happened when addGoods ...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, err.message));
                } else {

                    var data = JSON.parse(decodeURIComponent(result));

                    res.json(messageUtil.composeSucceededMessage(req, null, null));
                }
            });
        }
    })
};

/**
 * 修改商品状态
 * @param req
 * @param res
 */
exports.changeGoodsStatus = function (req, res) {
    var input = req.body;
    var map = {
        id: input.id,
        status: input.status
    }

    logger.info(req.body);
    productProxy.invoke('updateScoreShopByCondition', [map], function (err, result) {
        logger.info(err);
        if (err) {
            logger.error('Exception happened when changeGoodsStatus ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            //var data = JSON.parse(decodeURIComponent(result));

            logger.info(result);
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};

/**
 * 获取商品列表（后台）
 * @param req
 * @param res
 */
exports.getGoodsList = function (req, res) {

    var pageNo = Number(req.params.pageNo);

    productProxy.invoke('getScoreShopForPage', [pageNo], function (err, result) {
        if (err) {
            logger.error('Exception happened when getGoodsList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = JSON.parse(decodeURIComponent(result));

            var temp = {
                pages: Math.ceil(data.data.totalCount / 20),
                goodsList: data.data.productList
            };

            res.json(messageUtil.composeSucceededMessage(req, null, temp));
        }
    })
};

/**
 * 获取兑换记录列表
 */
exports.getExchangeRecordList = function (req, res) {

    var input = req.body;
    exchangeProxy.invoke('getScoreExchangeForPage', [input], function (err, result) {
        if (err) {
            logger.error('Exception happened when getExchangeRecordList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {


            var data = JSON.parse(decodeURIComponent(result));
            if (data.status != 0) {
                logger.error('getExchangeRecordList---' + data.msg)
                res.json(messageUtil.composeFailedMessage(req, data.msg));
            } else {

                loadListOfUser(data, function (err, data) {
                    if (err) {
                        res.json(messageUtil.composeFailedMessage(req, err[0].msg));
                    }
                    var temp = {
                        pages: Math.ceil(data.data.recordCount / 20),
                        recordList: data.data.recordList
                    };
                    res.json(messageUtil.composeSucceededMessage(req, null, temp));
                });

            }
        }
    })
};

var loadListOfUser = function (data, callback) {
    async.each(data.data.recordList, function (user, innerCallback) {
        Users.findById(user.userId, function (err, result) {
            if (err) {

            }
            user["communityName"] = result.community.communityName;
            innerCallback();
        }).populate("community", "communityName");

    }, function (err) {
        callback(err, data);
    })
}
exports.addScore = function (req, res) {
    var input = req.body;

    Users.findOne({_id: input.userId}, function (err, user) {
        if (err || user == null) {
            logger.error('addScore---无此用户')
            res.json(messageUtil.composeFailedMessage(req, '无此用户'));
        } else {
            var userRole = 1;
            if (user.userType == 'talent') {
                userRole = 2;
            }

            input.userRole = userRole;

            input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

            //scoreProxy.invoke('addScore', [input], function (err, result) {
            //    if (err) {
            //        logger.error('Exception happened when addScore ...!' + err.message);
            //        res.json(messageUtil.composeFailedMessage(req, err.message));
            //    } else {
            //        var data = JSON.parse(decodeURIComponent(result));
            //
            //        //toolUtil.putMessageGetuiPushMQ()
            //
            //        logger.info(data);
            //        res.json(messageUtil.composeSucceededMessage(req, null, null));
            //    }
            //});
        }
    });
};

exports.examineProduct = function (req, res) {
    var input = req.body;

    logger.info(input)

    exchangeProxy.invoke('examineProduct', [input], function (err, result) {
        if (err) {
            logger.error('Exception happened when getExchangeRecordList ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {

            var data = JSON.parse(decodeURIComponent(result));
            if (data.status != 0) {
                logger.error('examineProduct---' + data.msg)
                res.json(messageUtil.composeFailedMessage(req, data.msg));
            } else {

                logger.info(data.data);
                res.json(messageUtil.composeSucceededMessage(req, null, null));
            }
        }
    })
};

exports.addScoreManual = function (req, res) {
    var input = req.body;

    input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

    //scoreProxy.invoke('addScoreManual', [input], function (err, result) {
    //    if (err) {
    //        logger.error('Exception happened when addScoreManual ...!' + err.message);
    //        res.json(messageUtil.composeFailedMessage(req, err.message));
    //    } else {
    //        var data = JSON.parse(decodeURIComponent(result));
    //
    //        //toolUtil.putMessageGetuiPushMQ()
    //
    //        logger.info(data);
    //        res.json(messageUtil.composeSucceededMessage(req, null, null));
    //    }
    //});
};

exports.getDuibaUrl = function (req, res) {
    var token = req.params.token;
    scoreService.getDuibaUrl(token, function (err, result) {
        if (err) {
            logger.error('Exception happened when getDuibaUrl ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    })
};


exports.dedScore = function (req, res) {


    var input = {
        uid: req.cparams.uid,
        credits: req.cparams.credits,
        appKey: req.cparams.appKey,
        timestamp: req.cparams.timestamp,
        description: req.cparams.description,
        orderNum: req.cparams.orderNum,
        exchangeType: req.cparams.type,
        facePrice: req.cparams.facePrice,
        actualPrice: req.cparams.actualPrice,
        ip: req.cparams.ip,
        waitAudit: req.cparams.waitAudit,
        params: req.cparams.params,
        sign: req.cparams.sign
    };

    scoreService.dedScore(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when dedScore ...!' + err.message);
            res.json(result);
        } else {
            res.json(result);
        }
    })

};

exports.exchangeVirtualProduct = function (req, res) {


    var input = {
        appKey: req.cparams.appKey,
        orderNum: req.cparams.orderNum,
        developBizId: req.cparams.developBizId,
        uid: req.cparams.uid,
        params: req.cparams.params,
        timestamp: req.cparams.timestamp,
        sign: req.cparams.sign,
        description: req.cparams.description
    };

    scoreService.exchangeVirtualProduct(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when exchangeVirtualProduct ...!' + err.message);
            res.json(result);
        } else {
            res.json(result);
        }
    })

};


exports.getDuibaResult = function (req, res) {


    var input = {
        appKey: req.cparams.appKey,
        timestamp: req.cparams.timestamp,
        success: req.cparams.success,
        errorMessage: req.cparams.errorMessage,
        orderNum: req.cparams.orderNum,
        bizId: req.cparams.bizId,
        sign: req.cparams.sign
    };

    //logger.info(input);

    scoreService.getDuibaResult(input, function (err, result) {
        if (err) {
            logger.error('Exception happened when dedScore ...!' + err.message);
        }
    });
    res.send("ok");

};